<?php

namespace app\modules\api\controllers;
error_reporting(0);
use app\models\Agent;
use app\models\Isp;
use app\models\AgentPublish;
use app\models\AgentPackage;
use app\models\AgentAccount;
use app\models\ApiException;
use app\models\Card;
use app\models\CardAttr;
use app\models\CardAttrValue;
use app\models\CardReplace;
use app\models\CardStatusChange;
use app\models\CardDatalog;
use app\models\SubUser;
use app\models\User;
use app\models\Package;
use app\models\UserCardRecharge;
use app\models\UserCardReserveRecharge;
use app\models\MoneyChange;
use app\models\WaitActiveCard;
use app\models\ManagerLog;
use app\models\Util;
use Exception;
use yii\data\Pagination;
use Yii;
/**
 * 卡接口
 * Class CardController
 * @package app\modules\api\controllers
 */
class CardController extends BaseController
{
    /**
     * 依次尝试根据id ICCID MSISDN IMSI获取卡
     * @param Agent|User|SubUser $user 登录代理商或用户
     * @param string $jsonPrefix JSON数据路径前缀
     * @return Card
     * @throws ApiException
     */
    private function getCard($user = null, $jsonPrefix = '')
    {
        $id = $this->json($jsonPrefix . 'id');
        $iccid = $this->json($jsonPrefix . 'iccid');
        $msisdn = $this->json($jsonPrefix . 'msisdn');
        $imsi = $this->json($jsonPrefix . 'imsi');

        $card = null;
        if (!empty($id)) {
            $card = Card::findOne(['id' => $id]);
        } elseif (!empty($iccid)) {
            $iccidLength = strlen($iccid);
            if($iccidLength<19){
                $iccid = '-';
            }
            if($iccidLength>19){
            $iccid = substr($iccid,0,strlen($iccid)-1);
            }
            $card = Card::find()->andWhere(['like','iccid',$iccid])->one();
        } elseif (!empty($msisdn)) {
            $card = Card::findOne(['msisdn' => $msisdn]);
        } elseif (!empty($imsi)) {
            $card = Card::findOne(['imsi' => $imsi]);
        }

        if (!empty($card)) {
            if (!empty($user)) {
                if (($user instanceof SubUser) && in_array($user->uid, [3, 30]) && in_array($card->uid, [3, 30])) {
                    // loalandianzi laolan（两个账号各自的子账号都可以管理两个账号下的卡）
                    return $card;
                }

                return $card; // FIXME：暂时取消用户判断

                if (($user instanceof Agent) && $card->agent_id != $user->id) {
                    throw new ApiException('NOT_FOUND', '没有找到卡信息。');
                }
                if (($user instanceof User) && $card->uid != $user->id) {
                    throw new ApiException('NOT_FOUND', '没有找到卡信息。');
                }
                if (($user instanceof SubUser) && $card->uid != $user->uid) {
                    throw new ApiException('NOT_FOUND', '没有找到卡信息。');
                }
            }
        }

        return $card;
    }

    /**
     * 卡列表
     * 输入
     * {
     *   search_attr: [
     *     {name, value},
     *     ...
     *   ]
     * }
     * 示例：
     * ```JSON
     * {
     *   "search_attr": [
     *     {"name": "车牌号", "value": "鲁A12345"},
     *     {"name": "电话", "value": "15600000000"}
     *   ]
     * }
     * ```
     * 输出
     * {
     *   card_list: [
     *     {id, iccid, msisdn, imsi, package_id, status, active_time, on_off},
     *     ...
     *   ],
     *   page: {}
     * }
     * @throws ApiException
     */
    public function actionList()
    {
        $user = $this->loginUser();
        $uid = ($user instanceof User) ? $user->id : $user->uid;

        $query = Card::find();
        $query->andWhere(['uid' => $uid]);
        if (!empty($this->json('search_attr'))) {
            foreach ($this->json('search_attr') as $item) {
                $attrQuery = CardAttr::find()
                    ->distinct()
                    ->select('id')
                    ->andWhere(['uid' => $uid])
                    ->andWhere(['status' => CardAttr::STATUS_OK])
                    ->andWhere(['name' => $item['name']]);
                $attrValueQuery = CardAttrValue::find()
                    ->distinct()
                    ->select('card_id')
                    ->andWhere(['uid' => $uid])
                    ->andWhere(['attr_id' => $attrQuery])
                    ->andWhere(['value' => $item['value']]);
                $query->andWhere(['id' => $attrValueQuery]);
            }
        }
        $pagination = new Pagination(['totalCount' => $query->count(), 'page' => $this->json('page', 1) - 1, 'validatePage' => false]);
        $query->orderBy('id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $cardList = [];
        /** @var Card $card */
        foreach ($query->each() as $card) {
            $cardList[] = $card->getAttributes(['id', 'iccid', 'msisdn', 'imsi', 'package_id', 'status', 'active_time', 'on_off']);
        }
        return [
            'card_list' => $cardList,
            'page' => [
                'totalCount' => $pagination->totalCount,
                'pageCount' => $pagination->pageCount,
                'page' => $pagination->page + 1,
            ],
        ];
    }

    /**
     * 卡信息
     * 输入
     * {
     *     iccid,
     *     msisdn,
     *     imsi
     * }
     * 输出
     * {
     *     card: {
     *         id, api_id, iccid, msisdn, imsi, status,
     *         active_time, on_off, ip,
     *         data, sms, voice, refresh_time,
     *         term_length, term_length_unit, term_end_time
     *     },
     *     package: {
     *         id, name, data, sms, voice, price, extra_data, extra_data_price, extra_sms_price, extra_voice_price
     *     }
     * }
     * @throws ApiException
     */
    public function actionDetail()
    {
        $user = $this->loginUser();

        $card = $this->getCard($user);
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        return [
            'card' => $card->getAttributes(['id', 'iccid', 'msisdn', 'status', 'active_time', 'on_off', 'ip', 'data', 'total_flow', 'refresh_time', 'term_end_time']),
            'package' => empty($card->package_id) ? null : array_merge(
                $card->package->getAttributes(['id', 'name', 'data']),
                [
                    'price' => $card->package->getRealPrice($card),
                ]
            ),
        ];
    }
    public function actionTaocan(){
        $this->checkJson([
            [['username', 'password'], 'required','message' => '缺少必要参数。'],
        ]);

        $agent = Agent::findOne(['username'=>$this->json('username')])->getAttribute('id');
        $user = $this->loginUser();

        $res = (new \yii\db\Query())
        ->select(['package.id as id','package.name as name','package.data as data','agent_package.cost_price as cost_price','isp.id as isp_id','isp.name as isp_name','package.type as type'])
        ->from('package')
        ->join('join','agent_package','agent_package.package_id=package.id')
        ->join('join','isp','agent_package.isp=isp.id')
        ->andWhere(['agent_package.agent_id'=> $agent])
        ->all();
        foreach ($res as $key => $value) {
            $res[$key]['id'] = $res[$key]['id'];
            $res[$key]['name'] = $res[$key]['name'];
            $res[$key]['data'] = $res[$key]['data'];
            $res[$key]['isp_id'] = $res[$key]['isp_id'];
            $res[$key]['isp_name'] = $res[$key]['isp_name'];
            $res[$key]['type'] = $res[$key]['type'];
        }
        if($res){
            $data['code']="1";
            $data['msg']="操作成功";
            $data['data']=$res;
        }else{
            $data['code'] = "1001";
            $data['msg'] = "操作失败";
            $data['data']="";
        }
        return [
          'code'=>  $data['code'],
          'msg'=>  $data['msg'],
          'datas'=>  $data['data']
        ];
    }
    //代理商获取卡列表
    public function actionCardList(){
        $this->checkJson([
            [['username'], 'required','message' => '缺少必要参数。'],
        ]);
        $searchAgent = Agent::find()
                ->andWhere(['username' => $this->json('username')])
                ->one();
        $agentIdList = [$searchAgent->id];
        $agentIdList = array_merge($agentIdList, $searchAgent->getSubAidList());
        $user = $this->loginUser();
        $query = Card::find();
        $query->andWhere(['agent_id' => $agentIdList]);
        $pagination = new Pagination(['totalCount' => $query->count(), 'validatePage' => false]);
        $query->orderBy('id DESC');
        //$query->offset($pagination->offset)->limit($pagination->limit);
        $cardList = [];
        /** @var Card $card */
        foreach ($query->each() as $card) {
            $cardList[] = $card->getAttributes(['id','agent_id', 'iccid', 'msisdn', 'imsi', 'package_id', 'status','data','total_flow', 'active_time','term_end_time']);
        }
        return [
            'page' => [
                'totalCount' => $pagination->totalCount,
                //'pageCount' => $pagination->pageCount,
                //'page' => $pagination->page + 1,
            ],
            'card_list' => $cardList,
            
        ];
    }
    //代理商获取自己名下所有的代理商(包括代理下的代理)
    public function actionAgentList(){
        $this->checkJson([
            [['username'], 'required','message' => '缺少必要参数。'],
        ]);
        $agent_id = Agent::findOne(['username'=>$this->json('username')]);
        if($this->json('sub_agent') == '1'){
            $searchAgent = Agent::find()
                ->andWhere(['username' => $this->json('username')])
                ->one();
            $agentIdList = [$searchAgent->id];
            $agentIdList = array_merge($agentIdList, $searchAgent->getSubAidList());
            $list = Agent::find()->select('id,pid,username')->where(['id'=>$agentIdList])->all();
        }else{
            $list = Agent::find()->select('id,pid,username')->where(['pid'=>$agent_id->id])->all();
            
        }
        if($list){
            $data['code'] = '1';
            $data['msg'] = '操作成功';
            $data['data'] = $list;
        }
        return [
            'code' => $data['code'],
            'msg' => $data['msg'],
            'datas' => $data['data']
        ];

    }
    /**
     * 公开信息
     * 输入
     * {
     *     iccid,
     *     msisdn,
     *     imsi
     * }
     * 输出
     * {
     *     card: {
     *         id, api_id, agent_id, iccid, msisdn, imsi, status,
     *         active_time, on_off, ip,
     *         data, sms, voice, refresh_time,
     *         term_length, term_length_unit, term_end_time
     *     },
     *     package: {
     *         id, name, data, sms, voice, price, extra_data, extra_data_price, extra_sms_price, extra_voice_price
     *     },
     *     publish_list: [
     *         {id, name, type, value},
     *         ...
     *     ]
     * }
     * @throws ApiException
     */
    public function actionPublicDetail()
    {
        $card = $this->getCard();

        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        $publishList = [];
        /** @var AgentPublish $publish */
        foreach (AgentPublish::find()
            ->andWhere(['agent_id' => $card->agent_id])
            ->orderBy('sort DESC')
            ->each() as $publish) {
            $value = $publish->value;
            if (in_array($publish->type, [AgentPublish::TYPE_FILE, AgentPublish::TYPE_IMAGE])) {
                $value = Util::fileUrl($value);
            }
            $publishList[] = array_merge(
                $publish->getAttributes(['id', 'name', 'type']),
                ['value' => $value]
            );
        }

        return [
            'card' => $card->getAttributes(['id', 'api_id', 'uid', 'agent_id', 'iccid', 'msisdn', 'imsi', 'status', 'active_time', 'on_off', 'ip', 'data', 'sms', 'voice', 'refresh_time', 'term_length', 'term_length_unit', 'term_end_time']),
            'package' => empty($card->package_id) ? null : array_merge(
                $card->package->getAttributes(['id', 'name', 'data', 'sms', 'voice', 'extra_data', 'extra_data_price', 'extra_sms_price', 'extra_voice_price','type']),
                [
                    'price' => '15',
                ]
            ),
            'publish_list' => $publishList,
        ];
    }

    /**
     * 刷新卡
     * 输入
     * {
     *     iccid,
     *     msisdn,
     *     imsi
     * }
     * 输出
     * {}
     * @throws ApiException
     */
    public function actionRefresh()
    {
        $user = $this->loginUser();

        $card = $this->getCard($user);
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        try {
            $card->newrefreshBasic();
            return [];
        } catch (Exception $e) {
            throw new ApiException('SERVER', $e->getMessage());
        }
    }
    /**
     * 卡激活接口
     */
    public function actionActivecard(){
        if ($this->app_id != 'weixin') {
            throw new ApiException('FORBIDDEN', '没有权限。');
        }
        $card = $this->getCard(null, 'card/');
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        $st = $card->setActive($card->iccid);
        if($st){
            return [
                'code' => 1,
                'msg' => '激活成功',
                'data' => '',
            ];
            exit;
        }else{
            return [
                'code' => 1001,
                'msg' => '激活异常',
                'data' => '',
            ];
            exit;
        }

    }
    /**
     * 微信端刷新卡
     * 输入
     * {
     *     iccid,
     *     msisdn,
     *     imsi
     * }
     * 输出
     * {}
     * @throws ApiException
     */
    public function actionRefreshmy()
    {
        $user = $this->loginUser();

        $card = $this->getCardmy($user);
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        try {
            $card->newRefreshBasic();
            return [];
        } catch (Exception $e) {
            throw new ApiException('SERVER', $e->getMessage());
        }
    }
    
    /**
     * 刷新mifi，不计算时长
     */
    public function actionRefreshCard(){
        $user = $this->loginUser();

        $card = $this->getCardmy($user);
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        try {
            $card->newRefreshCard();
            return [];
        } catch (Exception $e) {
            throw new ApiException('SERVER', $e->getMessage());
        }
    }

    private function getCardmy($user = null, $jsonPrefix = '')
    {
    $id = $this->json($jsonPrefix . 'id');
    $iccid = $this->json($jsonPrefix . 'iccid');
    $msisdn = $this->json($jsonPrefix . 'msisdn');
    $imsi = $this->json($jsonPrefix . 'imsi');

    $card = null;
    if (!empty($id)) {
        $card = Card::findOne(['id' => $id]);
    } elseif (!empty($iccid)) {
        $iccidLength = strlen($iccid);
        if($iccidLength>19){
            $iccid = substr($iccid,0,strlen($iccid)-1);
        }
        $card = Card::find()->andWhere(['like','iccid',$iccid])->one();
    } elseif (!empty($msisdn)) {
        $card = Card::findOne(['msisdn' => $msisdn]);
    } elseif (!empty($imsi)) {
        $card = Card::findOne(['imsi' => $imsi]);
    }

    if (!empty($card)) {
        if (!empty($user)) {
            if (($user instanceof SubUser) && in_array($user->uid, [3, 30]) && in_array($card->uid, [3, 30])) {
                // loalandianzi laolan（两个账号各自的子账号都可以管理两个账号下的卡）
                return $card;
            }

            return $card; // FIXME：暂时取消用户判断

            if (($user instanceof Agent) && $card->agent_id != $user->id) {
                throw new ApiException('NOT_FOUND', '没有找到卡信息。');
            }
            if (($user instanceof User) && $card->uid != $user->id) {
                throw new ApiException('NOT_FOUND', '没有找到卡信息。');
            }
            if (($user instanceof SubUser) && $card->uid != $user->uid) {
                throw new ApiException('NOT_FOUND', '没有找到卡信息。');
            }
        }
    }

    return $card;
}
    /**
     * 设置卡状态
     * 输入
     * {
     *     iccid,
     *     msisdn,
     *     imsi,
     *     status
     * }
     * 输出
     * {}
     * @throws ApiException
     */
    public function actionSetStatus()
    {
        $user = $this->loginUser();
        
        $card = $this->getCard($user);
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        // $card->setStatus($this->json('status'));
        // CardStatusChange::info($card_id, $card->status, $this->json('status'), 3, 'uid=' . $user);
        try {
            $card->setStatus($this->json('status'));
            CardStatusChange::info($card_id, $card->status, $this->json('status'), 3, 'uid=' . $user);
        } catch (Exception $e) {
            throw new ApiException('SERVER', $e->getMessage());
        }
    }

    /**
     * 保存卡属性值
     * 输入
     * {
     *   card: {iccid},
     *   attr_list: [
     *     {name, value},
     *     ...
     *   ]
     * }
     * 输出
     * {}
     * @throws ApiException
     */
    public function actionSaveAttrValue()
    {
        $user = $this->loginUser('user');

        $this->checkJson([
            ['attr_list', 'required'],
        ]);

        $card = $this->getCard($user, 'card/');
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }

        foreach ($this->json('attr_list') as $item) {
            $name = $item['name'];
            $value = $item['value'];

            $attr = CardAttr::findOne(['uid' => $card->uid, 'name' => $name]);
            if (empty($attr)) {
                throw new ApiException('NOT_FOUND', '没有找到属性【' . $name . '】。');
            }
            $attrValue = CardAttrValue::findOne(['uid' => $card->uid, 'card_id' => $card->id, 'attr_id' => $attr->id]);
            if (empty($attrValue)) {
                $attrValue = new CardAttrValue();
                $attrValue->uid = $card->uid;
                $attrValue->card_id = $card->id;
                $attrValue->attr_id = $attr->id;
            }
            $attrValue->value = $value;
            if (!$attrValue->save()) {
                throw new ApiException('SERVER', '无法保存属性值。', $attrValue->errors);
            }
        }
        $card->updateAttributes(['attr_update_time' => time()]);

        return [];
    }

    /**
     * 卡替换
     * 输入
     * {
     *   old: {
     *     iccid
     *   },
     *   new: {
     *     iccid
     *   }
     * }
     * @throws ApiException
     */
    public function actionReplace()
    {
        $user = $this->loginUser();

        if (!($user instanceof SubUser)) {
            throw new ApiException('FORBIDDEN', '此接口仅限子用户使用。');
        }

        $oldCard = $this->getCard($user, 'old/');
        $newCard = $this->getCard($user, 'new/');
        if (empty($oldCard)) {
            throw new ApiException('NOT_FOUND', '没有找到旧卡信息。');
        }
        if (empty($newCard)) {
            throw new ApiException('NOT_FOUND', '没有找到新卡信息。');
        }

        $replace = new CardReplace();
        $replace->from_card_id = $oldCard->id;
        $replace->to_card_id = $newCard->id;
        $replace->require_sub_uid = $user->id;
        $replace->status = CardReplace::STATUS_WAIT;
        $replace->create_time = time();
        if (!$replace->save()) {
            throw new ApiException('SERVER', '无法保存卡替换信息。', $replace->errors);
        }

        return [];
    }

    /**
     * 充值
     * 输入
     * {
     *   card: {iccid, msisdn, imsi},
     *   term_length,
     *   price, money,
     *   trade_type, trade_no, trans_id,
     *   input, output, notify,
     *   extra_info: {username, tel, message}
     * }
     * 输出
     * {}
     * @throws ApiException
     */
    public function actionRecharge()
    {
        if ($this->app_id != 'weixin') {
            throw new ApiException('FORBIDDEN', '没有权限。');
        }

        $this->checkJson([
            [['card', 'term_length','package_id', 'price', 'money', 'trade_type', 'trade_no','source'], 'required'],
        ]);

        $card = $this->getCard(null, 'card/');
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        
        if (UserCardRecharge::find()->andWhere(['trade_no' => $this->json('trade_no')])->exists()) {
            throw new ApiException('TRADE_NO_REPEAT', '交易流水号重复。');
        }
        $package = Package::findOne(['id'=> $this->json('package_id')]);
        
        switch($package->length_unit){
            case '8';
                $term_length = 3;
                $endate = time() + (90*86400);
                $endtime = strtotime(date('Y-m-d',$endate))+86399;
                break;
            case '9';
                $term_length = 6;
                $endate = time() + (180*86400);
                $endtime = strtotime(date('Y-m-d',$endate))+86399;
                break;
            case '10';
                $term_length = 12;
                $endate = time() + (365*86400);
                $endtime = strtotime(date('Y-m-d',$endate))+86399;
                break;
            default:
                $term_length = 1;
                $endate = time() + (29*86400);
                $endtime = strtotime(date('Y-m-d',$endate))+86399;
                break;
        }
        //获取当前周期结束日期
        $end_date = time() + (29*86400);
        $end_time = strtotime(date('Y-m-d',$end_date))+86399;

        if($card->order_time == '0'){
            $order_time = time();
        }else{
            $order_time = $card->order_time;
        }
        $order_sn = date('YmdHis').rand(1000, 9999);
        //写入充值表
        $recharge = new UserCardRecharge();
        $recharge->uid = $card->uid;
        $recharge->agent_id = $card->agent_id;
        $recharge->package_id = $this->json('package_id');
        $recharge->card_id = $card->id;
        $recharge->term_length = $term_length;
        $recharge->term_length_unit = UserCardRecharge::TERM_LENGTH_UNIT_MONTH;
        $recharge->price = $this->json('price');
        $recharge->money = $this->json('money');
        $recharge->trade_type = $this->json('trade_type');
        $recharge->trade_no = $this->json('trade_no');
        $recharge->trans_id = $this->json('trans_id');
        $recharge->status = UserCardRecharge::STATUS_PAID;
        $recharge->create_time = time();
        $recharge->pay_time = time();
        $recharge->update_time = time();
        $recharge->source = $this->json('source');
        $recharge->open_id = $this->json('wx_open_id');
        if($card->term_end_time == '0'){
            if($card->dgcs == '0'){
                $recharge->recharge_type = '1';
            }
            
        }else{
            $recharge->recharge_type = '2';
        }
        $recharge->save();
        $id = $recharge->attributes['id'];
        $recharges = UserCardRecharge::findOne(['id' => $id]);
        $recharges->setPaid();    
        if($card->term_end_time == '0'){
            $dgcss = $card->dgcs + 1;
            if($package->length_unit == '12'){
                $enddates = time() + (7*86400);
                $endtimes = strtotime(date('Y-m-d',$enddates))+86399;    

                $card->updateAttributes(
                ['package_id'=>$this->json('package_id'),'active_time' => time(),'data'=>0,'term_length'=>1,'total_flow'=>$package->data,'term_end_time'=>$endtimes,'order_time'=>$order_time,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss, 'status' => Card::STATUS_ACTIVATED,'open_id'=>$this->json('wx_open_id'),'is_correct'=>0
                ]

            );
                $cardDatalog = new CardDatalog();
                $cardDatalog->card_id = $card->id;
                $cardDatalog->startdate = time();
                $cardDatalog->enddate = $enddates;
                $cardDatalog->order_sn = $order_sn;
                $cardDatalog->data = 0;
                $cardDatalog->saveExperienceDatalog();
            }else{
                $card->updateAttributes(
                ['package_id'=>$this->json('package_id'),'active_time' => time(),'data'=>0,'term_length'=>$term_length,'total_flow'=>$package->data,'term_end_time'=>$endtime,'order_time'=>$order_time,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss, 'status' => Card::STATUS_ACTIVATED,'open_id'=>$this->json('wx_open_id'),'is_correct'=>0
                ]
            );
            if($package->length_unit == '8' || $package->length_unit == '9' || $package->length_unit == '10'){
                    $cardDatalog = new CardDatalog();
                    $cardDatalog->card_id = $card->id;
                    $cardDatalog->startdate = time();
                    $cardDatalog->order_sn = $order_sn;
                    $cardDatalog->data = 0;
                    $cardDatalog->length_unit = $package->length_unit;
                    $cardDatalog->saveDataLogs();
                    
            }elseif($package->length_unit == '1' || $package->length_unit == '2' || $package->length_unit == '3'){
                $cardDatalog = new CardDatalog();
                $cardDatalog->card_id = $card->id;
                $cardDatalog->startdate = time();
                $cardDatalog->enddate = $endate;
                $cardDatalog->order_sn = $order_sn;
                $cardDatalog->data = 0;
                $cardDatalog->saveDataLog();   
                $orders = $this->setReserve($card->agent_id,$card->id,$card->iccid,$package->id,$end_time,$order_sn,$id,$this->json('source'),$package->length_unit);  
            }
            else{
                $cardDatalog = new CardDatalog();
                $cardDatalog->card_id = $card->id;
                $cardDatalog->startdate = time();
                $cardDatalog->enddate = $endate;
                $cardDatalog->order_sn = $order_sn;
                $cardDatalog->data = 0;
                $cardDatalog->saveDataLog();     
            }
            }
        
        }elseif(time() < $card->term_end_time){
            $dgcss = $card->dgcs + 1;
            $pack = $card->total_flow + $package->data;
            $unit = Package::findOne(['id'=> $card->package_id]);    
            if($unit->length_unit == '12'){
                $result = CardDatalog::deleteAll(['order_sn'=>$card->order_sn]);
                $card->updateAttributes(
                ['package_id'=>$this->json('package_id'),'active_time' => time(),'data'=>0,'term_length'=>1,'total_flow'=>$pack,'term_end_time'=>$endtime,'order_time'=>$order_time,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss, 'status' => Card::STATUS_ACTIVATED,'open_id'=>$this->json('wx_open_id'),'is_correct'=>0
                ]
            );
                $cardDatalog = new CardDatalog();
                $cardDatalog->card_id = $card->id;
                $cardDatalog->startdate = time();
                $cardDatalog->enddate = $endate;
                $cardDatalog->order_sn = $order_sn;
                $cardDatalog->data = 0;
                $cardDatalog->saveDataLog();
            }else{
                if($card->data > $card->total_flow){
                    $pack = $card->data + $package->data;
                }else{
                    $pack = $card->total_flow + $package->data;
                }
                $card->updateAttributes(['term_length'=>$term_length,'total_flow'=>$pack,'dgcs'=>$dgcss]);
                $second_recharge = $card->stopNetworkAccess($card->iccid);
                Yii::$app->db->createCommand()->update('card', ['limit_type'=>0], 'id = :id',['id' => $card->id])->execute();
            }         
            
        }elseif(time() > $card->term_end_time){
            $dgcss = $card->dgcs + 1;
            $card->updateAttributes(
                ['package_id'=>$this->json('package_id'),'active_time' => time(),'data'=>0,'term_length'=>$term_length,'total_flow'=>$package->data,'term_end_time'=>$endtime,'order_time'=>$order_time,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss, 'status' => Card::STATUS_ACTIVATED,'open_id'=>$this->json('wx_open_id'),'is_correct'=>0
                ]
            );
            if($package->length_unit == '8' || $package->length_unit == '9' || $package->length_unit == '10'){
                    $cardDatalog = new CardDatalog();
                    $cardDatalog->card_id = $card->id;
                    $cardDatalog->startdate = time();
                    $cardDatalog->order_sn = $order_sn;
                    $cardDatalog->data = 0;
                    $cardDatalog->length_unit = $package->length_unit;
                    $cardDatalog->saveDataLogs();
                    
                    
            }elseif($package->length_unit == '1' || $package->length_unit == '2' || $package->length_unit == '3'){
                $cardDatalog = new CardDatalog();
                $cardDatalog->card_id = $card->id;
                $cardDatalog->startdate = time();
                $cardDatalog->enddate = $endate;
                $cardDatalog->order_sn = $order_sn;
                $cardDatalog->data = 0;
                $cardDatalog->saveDataLog();   
                $orders = $this->setReserve($card->agent_id,$card->id,$card->iccid,$package->id,$end_time,$order_sn,$id,$this->json('source'));  
            }
            else{
                $cardDatalog = new CardDatalog();
                $cardDatalog->card_id = $card->id;
                $cardDatalog->startdate = time();
                $cardDatalog->enddate = $endate;
                $cardDatalog->order_sn = $order_sn;
                $cardDatalog->data = 0;
                $cardDatalog->saveDataLog();     
            }
            
        }
        if($package->length_unit == '99'){
            $active_card = $card->setActive($card->iccid);
        }else{
            //写入等待激活表
            $active = new WaitActiveCard();
            $active->iccid = $card->iccid;
            $active->recharge_id = $id;
            $active->agent_id = $card->agent_id;
            $active->package_id = $this->json('package_id');
            $active->price = $package->price;
            $active->trade_no = $order_sn;
            $active->source = $this->json('source');
            $active->create_time = time();
            $active->length_unit = $package->length_unit;
            $active->save();
        }
        
        //$active_card = $card->setActive($card->iccid);
        return [];
    }

    /**
     * MIFI执行写入和激活
     * 输入
     * {
     *   card: {iccid, msisdn, imsi},
     *   term_length,
     *   price, money,
     *   trade_type, trade_no, trans_id,
     *   input, output, notify,
     *   extra_info: {username, tel, message}
     * }
     * 输出
     * {}
     * @throws ApiException
     */
    public function actionRechargeYear()
    {
        if ($this->app_id != 'weixin') {
            throw new ApiException('FORBIDDEN', '没有权限。');
        }

        $this->checkJson([
            [['card', 'trade_type', 'source'], 'required'],
        ]);
        
        $card = $this->getCard(null, 'card/');
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        if($card->agent_id != 765){
            throw new ApiException('COULD_NOT_EXECUTE', '卡无法执行激活');
            exit;
        }
        // if (UserCardRecharge::find()->andWhere(['trade_no' => $this->json('trade_no')])->exists()) {
        //     throw new ApiException('TRADE_NO_REPEAT', '交易流水号重复。');
        // }
        $package = Package::findOne(['id'=> $card->package_id]);
        if(empty($package)){
            throw new ApiException('NO_PACKAGE', '没有设置套餐。');
            
        }
        if($card->active_time != 0){
            throw new ApiException('COULD_NOT_EXECUTE_TWICE', '卡已经激活，无法再次激活');
            exit;
        }

        $term_length = 1;
        $endate = time() + (29*86400);
        $endtime = strtotime(date('Y-m-d',$endate))+86399;
        
        //获取当前周期结束日期
        if($card->status != 4){
        $end_date = time() + (29*86400);
        $end_time = strtotime(date('Y-m-d',$end_date))+86399;
        if($card->order_time == '0'){
            $order_time = time();
        }else{
            $order_time = $card->order_time;
        }
        $order_sn = date('YmdHis').rand(1000, 9999);

        $recharge = new UserCardRecharge();
        $recharge->uid = $card->uid;
        $recharge->agent_id = $card->agent_id;
        $recharge->package_id = $package->id;
        $recharge->card_id = $card->id;
        $recharge->term_length = $term_length;
        $recharge->term_length_unit = UserCardRecharge::TERM_LENGTH_UNIT_MONTH;
        $recharge->price = $package->price;
        $recharge->money = $package->price;
        $recharge->trade_type = $this->json('trade_type');
        $recharge->trade_no = $order_sn;
        $recharge->trans_id = '';
        $recharge->status = UserCardRecharge::STATUS_PAID;
        $recharge->create_time = time();
        $recharge->pay_time = time();
        $recharge->update_time = time();
        $recharge->remark = '';
        $recharge->source = $this->json('source');
        if($card->term_end_time == '0'){
            if($card->dgcs == '0'){
                $recharge->recharge_type = '1';
            }
            
        }else{
            $recharge->recharge_type = '2';
        }

        $recharge->save();
        $id = $recharge->attributes['id'];
        $recharges = UserCardRecharge::findOne(['id' => $id]);
        $recharges->setPaid();  
           
        }
        if($card->term_end_time == '0'){
            $dgcss = $card->dgcs + 1;
                $card->updateAttributes(
                ['package_id'=>$package->id,'active_time' => time(),'data'=>0,'term_length'=>$term_length,'total_flow'=>$package->data,'term_end_time'=>$endtime,'order_time'=>$order_time,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss, 'status' => Card::STATUS_ACTIVATED
                ]
            );
                
                $cardDatalog = new CardDatalog();
                $cardDatalog->card_id = $card->id;
                $cardDatalog->startdate = time();
                $cardDatalog->enddate = $endate;
                $cardDatalog->order_sn = $order_sn;
                $cardDatalog->data = 0;
                $cardDatalog->saveDataLog();
                
            if($package->length_unit == 1){
                $orderSeason = $this->setReserverOrderSeason($card->agent_id,$card->id,$card->iccid,$package->id,$end_time,$order_sn,$id,$this->json('source'));
            }elseif($package->length_unit == 2){
                $orderYear = $this->setReserverOrderHalf($card->agent_id,$card->id,$card->iccid,$package->id,$end_time,$order_sn,$id,$this->json('source'));
            }elseif($package->length_unit == 3){
                $orders = $this->setReserverOrderYear($card->agent_id,$card->id,$card->iccid,$package->id,$end_time,$order_sn,$id,$this->json('source'));
            }
        }elseif(time() < $card->term_end_time){
            $dgcss = $card->dgcs + 1;
            $pack = $card->total_flow + $package->data;
            $unit = Package::findOne(['id'=> $card->package_id]);    
            if($unit->length_unit == 99){
                if($card->data > $card->total_flow){
                    $pack = $card->data + $package->data;
                }else{
                    $pack = $card->total_flow + $package->data;
                }
                $card->updateAttributes(['package_id'=>$package->id,'term_length'=>$term_length,'total_flow'=>$pack,'dgcs'=>$dgcss]);
            }         
            
        }elseif(time() > $card->term_end_time){
            $dgcss = $card->dgcs + 1;
            $card->updateAttributes(
                ['package_id'=>$package->id,'active_time' => time(),'data'=>0,'term_length'=>$term_length,'total_flow'=>$package->data,'term_end_time'=>$endtime,'order_time'=>$order_time,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss, 'status' => Card::STATUS_ACTIVATED
                ]
            );
                
                $cardDatalog = new CardDatalog();
                $cardDatalog->card_id = $card->id;
                $cardDatalog->startdate = time();
                $cardDatalog->enddate = $endate;
                $cardDatalog->order_sn = $order_sn;
                $cardDatalog->data = 0;
                $cardDatalog->saveDataLog();
                
            if($package->length_unit == 1){
                $orderSeason = $this->setReserverOrderSeason($card->agent_id,$card->id,$card->iccid,$package->id,$end_time,$order_sn,$id,$this->json('source'));
            }elseif($package->length_unit == 2){
                $orderYear = $this->setReserverOrderHalf($card->agent_id,$card->id,$card->iccid,$package->id,$end_time,$order_sn,$id,$this->json('source'));
            }elseif($package->length_unit == 3){
                $orders = $this->setReserverOrderYear($card->agent_id,$card->id,$card->iccid,$package->id,$end_time,$order_sn,$id,$this->json('source'));
            }
        }
        
        $active_card = $card->setActive($card->iccid);
        return [];
    }

    //铭信暂时使用代理充值接口
    /**
     * 代理商充值
     * 输入
     * {
     *   card: {iccid, msisdn, imsi},
     *   term_length,
     *   trade_type, trade_no, trans_id,
     *   input, output, notify,
     *   extra_info: {username, tel, message}
     * }
     * 输出
     * {}
     * @throws ApiException
     */
    public function actionAgentRecharge()
    {
        $this->checkJson([
            //[['card', 'package_id', 'trade_type', 'term_length','trade_no', 'source'], 'required'],
            [['card', 'term_length','package_id', 'price', 'money', 'trade_type', 'trade_no','source'], 'required'],
        ]);
        
        $user = $this->loginUser();
        //$card = $this->getCard($user);
        $card = $this->getCard(null, 'card/');
        if (empty($card)) {
            // throw new ApiException('NOT_FOUND', '没有找到卡信息。');
            $result['code'] = '1001';
            $result['msg'] = '没有找到卡信息';
            echo json_encode($result);
            exit;
        }
        
        if (UserCardRecharge::find()->andWhere(['trade_no' => $this->json('trade_no')])->exists()) {
            throw new ApiException('TRADE_NO_REPEAT', '交易流水号重复。');
        }
        $package = Package::findOne(['id'=> $this->json('package_id')]);
        $agentPackage = AgentPackage::findOne(['agent_id' => $card->agent_id, 'package_id' => $package->id]); 
        
        //判断代理商余额
        $money = AgentAccount::findOne(['agent_id'=>$card->agent_id]);
        $price = $money['money'] - $agentPackage->cost_price;
        if($price <= 0){
            $result['code'] = '1001';
            $result['msg'] = '您的账户余额不足！';
            echo json_encode($result);
            exit;
        }
        
        //计算到期时间
        $endate = time() + (29*86400);
        $endtime = strtotime(date('Y-m-d',$endate))+86399;
        $order_sn = date('YmdHis').rand(1000, 9999);
        //先执行写入充值表
        $recharge = new UserCardRecharge();
        $recharge->uid = $card->uid;
        $recharge->agent_id = $card->agent_id;
        $recharge->package_id = $this->json('package_id');
        $recharge->card_id = $card->id;
        $recharge->term_length = $this->json('term_length');
        $recharge->term_length_unit = UserCardRecharge::TERM_LENGTH_UNIT_MONTH;
        $recharge->price = $agentPackage->cost_price;
        $recharge->money = $this->json('money');
        $recharge->trade_type = $this->json('trade_type');
        $recharge->trade_no = $this->json('trade_no');
        $recharge->trans_id = $this->json('trans_id');
        $recharge->status = UserCardRecharge::STATUS_PAID;
        $recharge->create_time = time();
        $recharge->pay_time = time();
        $recharge->update_time = time();
        $recharge->input = $this->json('input');
        $recharge->output = $this->json('output');
        $recharge->notify = $this->json('notify');
        $recharge->remark = '';
        $recharge->source = $this->json('source');
        if($card->term_end_time == '0'){
            if($card->dgcs == '0'){
                $recharge->recharge_type = '1';
            }
        }elseif(time() < $card->term_end_time){
            if($package->length_unit == '0'){
                $recharge->recharge_type = '3';
            }elseif($package->length_unit == '99'){
                $recharge->recharge_type = '2';
            }
        }else{
            $recharge->recharge_type = '2';
        }
        $recharge->save();
        $id = $recharge->attributes['id'];
        $recharges = UserCardRecharge::findOne(['id' => $id]);
        $recharges->setPaid();

        if($card->term_end_time == '0'){
            if($package->type != '1'){
                $result['code'] = '1001';
                $result['msg'] = '首次充值请选择初始套餐！';
                echo json_encode($result);
                exit;
            }
            $dgcss = $card->dgcs + 1;
            $card->updateAttributes(
                ['package_id'=>$package->id,'active_time' => time(),'data'=>0,'term_length'=>1,'total_flow'=>$package->data,'term_end_time'=>$endtime,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss, 'status' => Card::STATUS_ACTIVATED
                ]
            );
            $cardDatalog = new CardDatalog();
            $cardDatalog->card_id = $card->id;
            $cardDatalog->startdate = time();
            $cardDatalog->enddate = $endate;
            $cardDatalog->order_sn = $order_sn;
            $cardDatalog->data = 0;
            $cardDatalog->saveDataLog();

        }elseif(time() > $card->term_end_time){
            if($package->type != '1'){
                $result['code'] = '1001';
                $result['msg'] = '首次充值请选择初始套餐！';
                echo json_encode($result);
                exit;
            }
            $dgcss = $card->dgcs + 1;
            $card->updateAttributes(
                ['package_id'=>$package->id,'active_time' => time(),'term_length'=>1,'data'=>0,'total_flow'=>$package->data,'term_end_time'=>$endtime,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss,'status' => Card::STATUS_ACTIVATED 
                ]
            );
            $cardDatalog = new CardDatalog();
            $cardDatalog->card_id = $card->id;
            $cardDatalog->startdate = time();
            $cardDatalog->enddate = $endate;
            $cardDatalog->order_sn = $order_sn;
            $cardDatalog->data = 0;
            $cardDatalog->saveDataLog();
        }elseif(time() < $card->term_end_time){
            if($package->length_unit != '99'){
               $agentreserve = $this->setAgentReserve($card->agent_id,$card->id,$card->iccid,$this->json('package_id'),$card->term_end_time,$order_sn,$id); 
           }elseif($package->length_unit == '99'){
                if($card->data > $card->total_flow){
                    $pack = $card->data + $package->data;
                }else{
                    $pack = $card->total_flow + $package->data;    
                }
                $card->updateAttributes(['term_length'=>1,'total_flow'=>$pack]);
           }
        }     
        
        $account = AgentAccount::findOne(['agent_id'=>$card->agent_id]);
        $account_money = $account->money - $agentPackage->cost_price;
        $account->money = $account_money;
        $account->save();
        //生成资金变动记录
        $moneychange = new MoneyChange();
        $moneychange->money_change = "-".$agentPackage->cost_price;;
        $moneychange->left_money = $account_money;
        $moneychange->recharge_number = $card->iccid;
        $moneychange->order_no = "DG".date('Ymd').time();
        $moneychange->create_time = time();
        $moneychange->money_source = 4;
        $moneychange->agent_id = $card->agent_id;
        $moneychange->save();
        //写入等待激活表
        if($recharges->recharge_type < 3){
            $active = new WaitActiveCard();
            $active->iccid = $card->iccid;
            $active->recharge_id = $id;
            $active->agent_id = $card->agent_id;
            $active->package_id = $this->json('package_id');
            $active->price = $agentPackage->cost_price;
            $active->trade_no = $order_sn;
            $active->source = $this->json('source');
            $active->create_time = time();
            $active->length_unit = $package->length_unit;
            $active->save();
        }
        
        return [];
    }
    //代理商充值接口
    /**
     * 代理商充值
     * 输入
     * {
     *   card: {iccid, msisdn, imsi},
     *   term_length,
     *   trade_type, trade_no, trans_id,
     *   input, output, notify,
     *   extra_info: {username, tel, message}
     * }
     * 输出
     * {}
     * @throws ApiException
     */
    public function actionAgentRecharges()
    {
        $this->checkJson([
            [['card', 'term_length','package_id', 'price', 'money', 'trade_type', 'trade_no','source'], 'required'],
        ]);
        
        $user = $this->loginUser();
        //$card = $this->getCard($user);
        $card = $this->getCard(null, 'card/');
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        
        if (UserCardRecharge::find()->andWhere(['trade_no' => $this->json('trade_no')])->exists()) {
            throw new ApiException('TRADE_NO_REPEAT', '交易流水号重复。');
        }
        $package = Package::findOne(['id'=> $this->json('package_id')]);
        $agentPackage = AgentPackage::findOne(['agent_id' => $card->agent_id, 'package_id' => $package->id]); 
        
        //判断代理商余额
        $money = AgentAccount::findOne(['agent_id'=>$card->agent_id]);
        $price = $money['money'] - $agentPackage->cost_price;
        if($price <= 0){
            $result['code'] = '1001';
            $result['msg'] = '您的账户余额不足！';
            echo json_encode($result);
            exit;
        }
        
        //获取本周期到期时间
        $endate = time() + (29*86400);
        $endtime = strtotime(date('Y-m-d',$endate))+86399;
        $order_sn = date('YmdHis').rand(1000, 9999);
        //先执行写入
        $recharge = new UserCardRecharge();
        $recharge->uid = $card->uid;
        $recharge->agent_id = $card->agent_id;
        $recharge->package_id = $this->json('package_id');
        $recharge->card_id = $card->id;
        $recharge->term_length = $this->json('term_length');
        $recharge->term_length_unit = UserCardRecharge::TERM_LENGTH_UNIT_MONTH;
        $recharge->price = $agentPackage->cost_price;
        $recharge->money = $agentPackage->sale_price;
        $recharge->trade_type = $this->json('trade_type');
        $recharge->trade_no = $this->json('trade_no');
        $recharge->trans_id = $this->json('trans_id');
        $recharge->status = UserCardRecharge::STATUS_PAID;
        $recharge->create_time = time();
        $recharge->pay_time = time();
        $recharge->update_time = time();
        $recharge->input = $this->json('input');
        $recharge->output = $this->json('output');
        $recharge->notify = $this->json('notify');
        $recharge->remark = '';
        $recharge->source = $this->json('source');
        if($card->dgcs == '0'){
            $recharge->recharge_type = '1';
        }else{
            $recharge->recharge_type = '2';
        }
        $recharge->save();
        $id = $recharge->attributes['id'];
          
        if($card->term_end_time == '0'){
            if($package->type != '1'){
                $result['code'] = '1001';
                $result['msg'] = '首次充值请选择初始套餐！';
                echo json_encode($result);
                exit;
            }
            $dgcss = $card->dgcs + 1;
            $card->updateAttributes(
                ['package_id'=>$package->id,'active_time' => time(),'data'=>0,'term_length'=>1,'total_flow'=>$package->data,'term_end_time'=>$endtime,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss, 'status' => Card::STATUS_ACTIVATED
                ]
            );
            $cardDatalog = new CardDatalog();
            $cardDatalog->card_id = $card->id;
            $cardDatalog->startdate = time();
            $cardDatalog->enddate = $endate;
            $cardDatalog->order_sn = $order_sn;
            $cardDatalog->data = 0;
            $cardDatalog->saveDataLog();

        }elseif(time() > $card->term_end_time){
            if($package->type != '1'){
                $result['code'] = '1001';
                $result['msg'] = '首次充值请选择初始套餐！';
                echo json_encode($result);
                exit;
            }
            $dgcss = $card->dgcs + 1;
            $card->updateAttributes(
                ['package_id'=>$package->id,'active_time' => time(),'term_length'=>1,'data'=>0,'total_flow'=>$package->data,'term_end_time'=>$endtime,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss,'status' => Card::STATUS_ACTIVATED 
                ]
            );
            $cardDatalog = new CardDatalog();
            $cardDatalog->card_id = $card->id;
            $cardDatalog->startdate = time();
            $cardDatalog->enddate = $endate;
            $cardDatalog->order_sn = $order_sn;
            $cardDatalog->data = 0;
            $cardDatalog->saveDataLog();
        }elseif(time() < $card->term_end_time){
            if($card->package_id != null && $package->length_unit != '99'){
                $result['code'] = '1001';
                $result['msg'] = '您有初始套餐，请充值加油包';
                echo json_encode($result);
                exit;
           }elseif($package->length_unit == '99'){
                if($card->data > $card->total_flow){
                    $pack = $card->data + $package->data;
                }else{
                    $pack = $card->total_flow + $package->data;    
                }
                $card->updateAttributes(['package_id'=>$package->id,'term_length'=>1,'total_flow'=>$pack]);
           }
        }     
        
        $account = AgentAccount::findOne(['agent_id'=>$card->agent_id]);
        $account_money = $account->money - $agentPackage->cost_price;
        $account->money = $account_money;
        $account->save();
        //生成资金变动记录
        $moneychange = new MoneyChange();
        $moneychange->money_change = "-".$agentPackage->cost_price;;
        $moneychange->left_money = $account_money;
        $moneychange->recharge_number = $card->iccid;
        $moneychange->order_no = "DG".date('Ymd').time();
        $moneychange->create_time = time();
        $moneychange->money_source = 4;
        $moneychange->agent_id = $card->agent_id;
        $moneychange->save();
        $recharges = UserCardRecharge::findOne(['id' => $id]);
        $recharges->setPaid();  
        $active_card = $card->setActive($card->iccid);
        return [];
    }
    /**
     * 执行预充值
     * @throws ApiException
     */
    public function actionAgentReserveRecharge()
    {
        if ($this->app_id != 'weixin') {
            throw new ApiException('FORBIDDEN', '没有权限。');
        }

        $this->checkJson([
            [['card', 'term_length','package_id', 'price', 'money', 'trade_type', 'trade_no','source'], 'required'],
        ]);

        $card = $this->getCard(null, 'card/');
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        $reserve = UserCardReserveRecharge::find()->orderBy('id asc')->andWhere(['like','iccid',$card->iccid])->andWhere(['execute_status'=>2])->one();
        $package = Package::findOne(['id'=> $reserve['package_id']]);

        //获取本周期到期时间
        $endate = time() + (29*86400);
        $endtime = strtotime(date('Y-m-d',$endate))+86399;           
        if(empty($reserve)){
            $order_sn = date('YmdHis').rand(1000, 9999);
        }else{
            $order_sn = $reserve['order_sn'];
            $package_id = $reserve['package_id'];
        }
        
        $dgcss = $card->dgcs + 1;
        if($reserve['package_id'] == '84'){
            $data = $card->data;
            $total_flow = $card->total_flow;
            $card->updateAttributes(
            ['package_id'=>$package_id,'active_time' => time(),'term_length'=>1,'data'=>$data,'total_flow'=>$total_flow,'term_end_time'=>$endtime,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss, 'status' => Card::STATUS_ACTIVATED,'is_correct'=>0
            ]
        );
        }elseif($package->length_unit == '8' || $package->length_unit == '9' || $package->length_unit == '10'){
            $card->updateAttributes(
                ['package_id'=>$package_id,'data'=>0,'term_length_unit'=>3,'status' => Card::STATUS_ACTIVATED,'is_correct'=>0] 
            );
        }else{
           $card->updateAttributes(
            ['package_id'=>$package_id,'active_time' => time(),'term_length'=>1,'data'=>0,'total_flow'=>$package->data,'term_end_time'=>$endtime,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss, 'status' => Card::STATUS_ACTIVATED,'is_correct'=>0
            ]
        ); 
        }
        if($package->length_unit != '8' || $package->length_unit != '9' || $package->length_unit != '10'){
            $cardDatalog = new CardDatalog();
            $cardDatalog->card_id = $card->id;
            $cardDatalog->startdate = time();
            $cardDatalog->enddate = $endate;
            $cardDatalog->order_sn = $order_sn;
            $cardDatalog->data = 0;
            $cardDatalog->saveDataLog(); 
        }
        
        Yii::$app->db->createCommand()->update('user_card_reserve_recharge', ['execute_status' => 1,'execute_time' => time()], 'id = :id',['id' => $reserve['id']])->execute();  
       
        $recharge = new UserCardRecharge();
        $recharge->uid = $card->uid;
        $recharge->agent_id = $card->agent_id;
        $recharge->package_id = $reserve['package_id'];
        $recharge->card_id = $card->id;
        $recharge->term_length = $this->json('term_length');
        $recharge->term_length_unit = UserCardRecharge::TERM_LENGTH_UNIT_MONTH;
        $recharge->price = $this->json('price');
        $recharge->money = $this->json('money');
        $recharge->trade_type = $this->json('trade_type');
        $recharge->trade_no = $this->json('trade_no');
        $recharge->trans_id = $this->json('trans_id');
        $recharge->status = UserCardRecharge::STATUS_RECHARGE;
        $recharge->create_time = time();
        $recharge->pay_time = time();
        $recharge->update_time = time();
        $recharge->input = $this->json('input');
        $recharge->output = $this->json('output');
        $recharge->notify = $this->json('notify');
        $recharge->remark = '';
        $recharge->source = $reserve['source'];
        $recharge->is_show = '0';
        $recharge->recharge_parent_id = $reserve['card_recharge_id'];
        $recharge->recharge_type = '4';
        $recharge->save();
        ManagerLog::info('1', '执行预充值', print_r($recharge->attributes, true));
        //判断是否执行解除限速操作
        if($card->limit_type == 1){
            $package = Package::findOne(['id'=>$reserve['package_id']]);
            if($package->data == 0 && $package->limit_type == 1){
                exit;
            }else{
                $second_recharge = $card->stopNetworkAccess($card->iccid);
                Yii::$app->db->createCommand()->update('card', ['limit_type' => 0], 'id = :id',['id' => $card->id])->execute();
            }
        }
        //写入等待激活表执行激活和校正流量
        $active = new WaitActiveCard();
        $active->iccid = $reserve->iccid;
        $active->recharge_id = $reserve->card_recharge_id;
        $active->agent_id = $reserve->agent_id;
        $active->package_id = $reserve->package_id;
        $active->price = $package->price;
        $active->trade_no = $order_sn;
        $active->source = $reserve->source;
        $active->create_time = time();
        $active->fail_number = 0;
        $active->is_refresh = 0;
        $active->length_unit = 0;
        $active->save();
        //$active_card = $card->setActive($card->iccid);
        return [];
    }
    //代理商预定接口
    public function actionAgentReserve()
    {
        $this->checkJson([
            [['card', 'package_id', 'trade_type', 'term_length','trade_no', 'source'], 'required'],
        ]);
        
        $user = $this->loginUser();
        //$card = $this->getCard($user);
        $card = $this->getCard(null, 'card/');
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        
        if (UserCardReserveRecharge::find()->andWhere(['trade_no' => $this->json('trade_no')])->exists()) {
            throw new ApiException('TRADE_NO_REPEAT', '交易流水号重复。');
        }
        $package = Package::findOne(['id'=> $this->json('package_id')]);
        
        $order_sn = date('YmdHis').rand(1000, 9999);
        if($package->length_unit == '99'){
            $result['code'] = '1001';
            $result['msg'] = '加油包套餐无法预定';
            echo json_encode($result);
            exit;
        }
        if($card->term_end_time == '0'){
            $result['code'] = '1001';
            $result['msg'] = '您尚未充值，无法预定';
            echo json_encode($result);
            exit;
        }
        if(time() > $card->term_end_time){
            $result['code'] = '1001';
            $result['msg'] = '您的卡已经到期，无法预定，请充值基础套餐';
            echo json_encode($result);
            exit;
        }
        //外键关联不能删除，插入一条
        $ucharge = new UserCardRecharge();
        $ucharge->agent_id = $card->agent_id;
        $ucharge->card_id = $card->id;
        $ucharge->term_length = $this->json('term_length');
        $ucharge->term_length_unit = UserCardRecharge::TERM_LENGTH_UNIT_MONTH;
        $ucharge->price = $this->json('price');
        $ucharge->money = $this->json('money');
        $ucharge->trade_type = $this->json('trade_type');
        $ucharge->trade_no = $this->json('trade_no');
        $ucharge->package_id = $this->json('package_id');
        $ucharge->status = UserCardRecharge::STATUS_PAID;
        $ucharge->create_time = time();
        $ucharge->pay_time = time();
        $ucharge->source = $this->json('source');
        $ucharge->recharge_type = '3';
        $ucharge->save();
        $id = $ucharge->attributes['id'];
        $recharges = UserCardRecharge::findOne(['id' => $id]);
        $recharges->setPaid();
        
        //单月套餐存入预定充值表
        $last = UserCardReserveRecharge::find()->orderBy('id desc')->andWhere(['like','iccid',$card->iccid])->andWhere(['execute_status'=>2])->one();
        if($last){
            $k = 1;
            $active_time = $last['term_end_time'] + 1;
            $endtime = strtotime(date("Y-m-d",strtotime('+'.$k.'month',$active_time))) - 1;
        }else{
            $k = 1;
            $active_time = $card->term_end_time + 1;
            $endtime = strtotime(date("Y-m-d",strtotime('+'.$k.'month',$active_time))) - 1;
        }
        
        $recharge = new UserCardReserveRecharge();
        $recharge->uid = $card->uid;
        $recharge->agent_id = $card->agent_id;
        $recharge->package_id = $this->json('package_id');
        $recharge->card_id = $card->id;
        $recharge->iccid = $card->iccid;
        $recharge->term_length = $this->json('term_length');
        $recharge->term_length_unit = UserCardReserveRecharge::TERM_LENGTH_UNIT_MONTH;
        $recharge->price = $this->json('price');
        $recharge->money = $this->json('money');
        $recharge->trade_type = $this->json('trade_type');
        $recharge->trade_no = $this->json('trade_no');
        $recharge->status = UserCardReserveRecharge::STATUS_PAID;
        $recharge->create_time = time();
        $recharge->pay_time = time();
        $recharge->active_time = $active_time;
        $recharge->term_end_time = $endtime;
        $recharge->source = $this->json('source');
        $recharge->order_sn = $order_sn;
        $recharge->card_recharge_id = $id;
        $recharge->recharge_type = '3';
        $recharge->save();
        return [];
    }
    /**
     * 微信端预定充值
     * 输入
     * {
     *   card: {iccid, msisdn, imsi},
     *   term_length,
     *   price, money,
     *   trade_type, trade_no, trans_id,
     *   input, output, notify,
     *   extra_info: {username, tel, message}
     * }
     * 输出
     * {}
     * @throws ApiException
     */
    public function actionReserveRecharge()
    {
        if ($this->app_id != 'weixin') {
            throw new ApiException('FORBIDDEN', '没有权限。');
        }

        $this->checkJson([
            [['card', 'term_length','package_id', 'price', 'money', 'trade_type', 'trade_no','source'], 'required'],
        ]);

        $card = $this->getCard(null, 'card/');
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        
        if (UserCardReserveRecharge::find()->andWhere(['trade_no' => $this->json('trade_no')])->exists()) {
            throw new ApiException('TRADE_NO_REPEAT', '交易流水号重复。');
        }
        $package = Package::findOne(['id'=> $this->json('package_id')]);
        $order_sn = date('YmdHis').rand(1000, 9999);
        //外键关联不能删除，插入一条
        $ucharge = new UserCardRecharge();
        $ucharge->agent_id = $card->agent_id;
        $ucharge->card_id = $card->id;
        $ucharge->term_length = $this->json('term_length');
        $ucharge->term_length_unit = UserCardRecharge::TERM_LENGTH_UNIT_MONTH;
        $ucharge->price = $this->json('price');
        $ucharge->money = $this->json('money');
        $ucharge->trade_type = $this->json('trade_type');
        $ucharge->trade_no = $this->json('trade_no');
        $ucharge->package_id = $this->json('package_id');
        $ucharge->status = UserCardRecharge::STATUS_PAID;
        $ucharge->create_time = time();
        $ucharge->pay_time = time();
        $ucharge->update_time = time();
        $ucharge->source = $this->json('source');
        $ucharge->open_id = $this->json('wx_open_id');
        $ucharge->recharge_type = '3';
        $ucharge->save();
        $id = $ucharge->attributes['id'];
        $recharges = UserCardRecharge::findOne(['id' => $id]);
        $recharges->setPaid();
        
        //单月套餐存入预定充值表
        $last = UserCardReserveRecharge::find()->orderBy('id desc')->andWhere(['like','iccid',$card->iccid])->andWhere(['execute_status'=>2])->one();
        if($last){
            $k = 1;
            $active_time = $last['active_time'] + (30*86400);
        }else{
            $k = 1;
            $active_time = $card->term_end_time + 1;
        }
        
        //年套餐存入预定充值表
        if($package->length_unit == '1' || $package->length_unit == '2' || $package->length_unit == '3'){
           $orders = $this->setReserveRecharge($card->agent_id,$card->id,$card->iccid,$package->id,$active_time,$order_sn,$id,$this->json('source'));   
        }elseif($package->length_unit == 0){
            $recharge = new UserCardReserveRecharge();
            $recharge->uid = $card->uid;
            $recharge->agent_id = $card->agent_id;
            $recharge->package_id = $this->json('package_id');
            $recharge->card_id = $card->id;
            $recharge->iccid = $card->iccid;
            $recharge->term_length = $this->json('term_length');
            $recharge->term_length_unit = UserCardReserveRecharge::TERM_LENGTH_UNIT_MONTH;
            $recharge->price = $this->json('price');
            $recharge->money = $this->json('money');
            $recharge->trade_type = $this->json('trade_type');
            $recharge->trade_no = $this->json('trade_no');
            $recharge->status = UserCardReserveRecharge::STATUS_PAID;
            $recharge->create_time = time();
            $recharge->pay_time = time();
            $recharge->active_time = $active_time;
            $recharge->source = $this->json('source');
            $recharge->order_sn = $order_sn;
            $recharge->card_recharge_id = $id;
            $recharge->save();
        }
        return [];
    }
    
    public function actionRechargeOrder()
    {
        if ($this->app_id != 'weixin') {
            throw new ApiException('FORBIDDEN', '没有权限。');
        }
        $this->checkJson([
            [['card', 'term_length','package_id', 'price', 'money', 'trade_type', 'trade_no','source'], 'required'],
        ]);

        $card = $this->getCard(null, 'card/');
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        
        if (UserCardRecharge::find()->andWhere(['trade_no' => $this->json('trade_no')])->exists()) {
            throw new ApiException('TRADE_NO_REPEAT', '交易流水号重复。');
        }
        $reserve = UserCardReserveRecharge::findOne(['card_id'=>$card->id,'execute_status'=>2]);
        $package = Package::findOne(['id'=> $this->json('package_id')]);
        
        //获取本周期到期时间
        $endate = time() + (29*86400);
        $endtime = strtotime(date('Y-m-d',$endate))+86399;    
        if($card->order_time == '0'){
            $order_time = time();
        }else{
            $order_time = $card->order_time;
        }
        $order_sn = date('YmdHis').rand(1000, 9999);

        $recharge = new UserCardRecharge();
        $recharge->uid = $card->uid;
        $recharge->agent_id = $card->agent_id;
        $recharge->package_id = $this->json('package_id');
        $recharge->card_id = $card->id;
        $recharge->term_length = $this->json('term_length');
        $recharge->term_length_unit = UserCardRecharge::TERM_LENGTH_UNIT_MONTH;
        $recharge->price = $this->json('price');
        $recharge->money = $this->json('money');
        $recharge->trade_type = $this->json('trade_type');
        $recharge->trade_no = $this->json('trade_no');
        $recharge->trans_id = $this->json('trans_id');
        $recharge->status = UserCardRecharge::STATUS_PAID;
        $recharge->create_time = time();
        $recharge->pay_time = time();
        $recharge->update_time = time();
        $recharge->input = $this->json('input');
        $recharge->output = $this->json('output');
        $recharge->notify = $this->json('notify');
        $recharge->remark = json_encode($this->json('extra_info'));
        $recharge->source = $this->json('source');
        $recharge->recharge_type = '3';
        $recharge->save();
        $id = $recharge->attributes['id'];
        $recharges = UserCardRecharge::findOne(['id' => $id]);
        $recharges->setPaid();

        if($this->json('package_id') == '36'){
           $package->id = '33'; 
           $package = Package::findOne(['id'=> $package->id]);
           $package->data = $package->data;
        }
        if($card->term_end_time == '0'){  
            $dgcss = $card->dgcs + 1;
            $card->updateAttributes(
                ['package_id'=>$package->id,'active_time' => time(),'data'=>0,'term_length'=>1,'total_flow'=>$package->data,'term_end_time'=>$endtime,'order_time'=>$order_time,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss, 'status' => Card::STATUS_ACTIVATED
                ]
            );
            $cardDatalog = new CardDatalog();
            $cardDatalog->card_id = $card->id;
            $cardDatalog->startdate = time();
            $cardDatalog->enddate = $endate;
            $cardDatalog->order_sn = $order_sn;
            $cardDatalog->data = 0;
            $cardDatalog->saveDataLog();
            if($this->json('package_id') == '36'){
                $package->id = '33';
                $ad = $this->setReserver($card->agent_id,$card->id,$card->iccid,$package->id,$endtime,$order_sn,$id,$this->json('source'));
            }
            
        }elseif(time() < $card->term_end_time){
            $dgcss = $card->dgcs + 1;
            if($card->data > $card->total_flow){
                $pack = $card->data + $package->data;
            }else{
                $pack = $card->total_flow + $package->data;
            }
            $length = $card->term_length;
            $card->updateAttributes(['package_id'=>$this->json('package_id'),'term_length'=>$length,'total_flow'=>$pack,'dgcs'=>$dgcss]);
            $second_recharge = $card->stopNetworkAccess($card->iccid);
            Yii::$app->db->createCommand()->update('card', ['limit_type'=>0], 'id = :id',['id' => $card->id])->execute();
            
        }

        $active_card = $card->setActive($card->iccid);
        return [];
    }
    //年包充值类型2，每个月都是30G
    public function actionRechargeOrders()
    {
        if ($this->app_id != 'weixin') {
            throw new ApiException('FORBIDDEN', '没有权限。');
        }

        $this->checkJson([
            [['card', 'term_length','package_id', 'price', 'money', 'trade_type', 'trade_no','source'], 'required'],
        ]);

        $card = $this->getCard(null, 'card/');
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        
        // if (UserCardRecharge::find()->andWhere(['trade_no' => $this->json('trade_no')])->exists()) {
        //     throw new ApiException('TRADE_NO_REPEAT', '交易流水号重复。');
        // }
        $reserve = UserCardReserveRecharge::findOne(['card_id'=>$card->id,'execute_status'=>2]);
        if($this->json('package_id') == '44'){
            $id = "45";
            $package = Package::findOne(['id'=>$id]);
        }else{
            $package = Package::findOne(['id'=> $this->json('package_id')]);
        }        
        //获取本周期到期时间
        $endate = time() + (29*86400);
        $endtime = strtotime(date('Y-m-d',$endate))+86399;
            
        if($card->order_time == '0'){
            $order_time = time();
        }else{
            $order_time = $card->order_time;
        }
        $order_sn = date('YmdHis').rand(1000, 9999);
        //先存入卡充值表
        $recharge = new UserCardRecharge();
        $recharge->uid = $card->uid;
        $recharge->agent_id = $card->agent_id;
        $recharge->package_id = $this->json('package_id');
        $recharge->card_id = $card->id;
        $recharge->term_length = $this->json('term_length');
        $recharge->term_length_unit = UserCardRecharge::TERM_LENGTH_UNIT_MONTH;
        $recharge->price = $this->json('price');
        $recharge->money = $this->json('money');
        $recharge->trade_type = $this->json('trade_type');
        $recharge->trade_no = $this->json('trade_no');
        $recharge->trans_id = $this->json('trans_id');
        $recharge->status = UserCardRecharge::STATUS_PAID;
        $recharge->create_time = time();
        $recharge->pay_time = time();
        $recharge->update_time = time();
        $recharge->input = $this->json('input');
        $recharge->output = $this->json('output');
        $recharge->notify = $this->json('notify');
        $recharge->remark = json_encode($this->json('extra_info'));
        $recharge->source = $this->json('source');
        $recharge->save();
        $id = $recharge->attributes['id'];
        $recharges = UserCardRecharge::findOne(['id' => $id]);
        $recharges->setPaid();

        if($card->term_end_time == '0'){  
            $dgcss = $card->dgcs + 1;
            $card->updateAttributes(
                ['package_id'=>$package->id,'active_time' => time(),'data'=>0,'term_length'=>1,'total_flow'=>$package->data,'term_end_time'=>$endtime,'order_time'=>$order_time,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss, 'status' => Card::STATUS_ACTIVATED
                ]
            );
            $cardDatalog = new CardDatalog();
            $cardDatalog->card_id = $card->id;
            $cardDatalog->startdate = time();
            $cardDatalog->enddate = $endate;
            $cardDatalog->order_sn = $order_sn;
            $cardDatalog->data = 0;
            $cardDatalog->saveDataLog();
            if($this->json('package_id') == '44'){
                $package->id = '45';
                $orders = $this->setReserverOrder($card->agent_id,$card->id,$card->iccid,$package->id,$endtime,$order_sn,$id,$this->json('source'));
            }
            
        }elseif(time() < $card->term_end_time){
            $dgcss = $card->dgcs + 1;
            if($card->data > $card->total_flow){
                $pack = $card->data + $package->data;
            }else{
                $pack = $card->total_flow + $package->data;
            }
            $length = $card->term_length;
            $card->updateAttributes(['package_id'=>$this->json('package_id'),'term_length'=>$length,'total_flow'=>$pack,'dgcs'=>$dgcss]);
        }
        $active_card = $card->setActive($card->iccid);
        return [];
    }
    //年包半年包充值
    public function actionRechargeOrderYear()
    {
        if ($this->app_id != 'weixin') {
            throw new ApiException('FORBIDDEN', '没有权限。');
        }

        $this->checkJson([
            [['card', 'term_length','package_id', 'price', 'money', 'trade_type', 'trade_no','source'], 'required'],
        ]);

        $card = $this->getCard(null, 'card/');
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        
        if (UserCardRecharge::find()->andWhere(['trade_no' => $this->json('trade_no')])->exists()) {
            throw new ApiException('TRADE_NO_REPEAT', '交易流水号重复。');
        }
        $package = Package::findOne(['id'=> $this->json('package_id')]);
        $reserve = UserCardReserveRecharge::findOne(['card_id'=>$card->id,'execute_status'=>2]);
        
        //获取本周期到期时间
        $endate = time() + (29*86400);
        $endtime = strtotime(date('Y-m-d',$endate))+86399;
            
        if($card->order_time == '0'){
            $order_time = time();
        }else{
            $order_time = $card->order_time;
        }
        $order_sn = date('YmdHis').rand(1000, 9999);
        //先存入卡充值表
        $recharge = new UserCardRecharge();
        $recharge->uid = $card->uid;
        $recharge->agent_id = $card->agent_id;
        $recharge->package_id = $this->json('package_id');
        $recharge->card_id = $card->id;
        $recharge->term_length = $this->json('term_length');
        $recharge->term_length_unit = UserCardRecharge::TERM_LENGTH_UNIT_MONTH;
        $recharge->price = $this->json('price');
        $recharge->money = $this->json('money');
        $recharge->trade_type = $this->json('trade_type');
        $recharge->trade_no = $this->json('trade_no');
        $recharge->trans_id = $this->json('trans_id');
        $recharge->status = UserCardRecharge::STATUS_PAID;
        $recharge->create_time = time();
        $recharge->pay_time = time();
        $recharge->update_time = time();
        $recharge->input = $this->json('input');
        $recharge->output = $this->json('output');
        $recharge->notify = $this->json('notify');
        $recharge->remark = json_encode($this->json('extra_info'));
        $recharge->source = $this->json('source');
        if($card->term_end_time == '0'){
            if($card->dgcs == '0'){
                $recharge->recharge_type = '1';
            }    
        }else{
            $recharge->recharge_type = '2';
        }
        $recharge->save();
        $id = $recharge->attributes['id'];
        $recharges = UserCardRecharge::findOne(['id' => $id]);
        $recharges->setPaid();      
        if($card->term_end_time == '0'){  
            $dgcss = $card->dgcs + 1;
            $card->updateAttributes(
                ['package_id'=>$this->json('package_id'),'active_time' => time(),'data'=>0,'term_length'=>1,'total_flow'=>$package->data,'term_end_time'=>$endtime,'order_time'=>$order_time,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss, 'status' => Card::STATUS_ACTIVATED
                ]
            );
            $cardDatalog = new CardDatalog();
            $cardDatalog->card_id = $card->id;
            $cardDatalog->startdate = time();
            $cardDatalog->enddate = $endate;
            $cardDatalog->order_sn = $order_sn;
            $cardDatalog->data = 0;
            $cardDatalog->saveDataLog();
            if($this->json('package_id') == '47' || $this->json('package_id') == '49'){
                $package->id = '51';
                $orders = $this->setReserverOrderYear($card->agent_id,$card->id,$card->iccid,$package->id,$endtime,$order_sn,$id,$this->json('source'));
            }else{
                $package->id = '51';
                $orderYear = $this->setReserverOrderHalf($card->agent_id,$card->id,$card->iccid,$package->id,$endtime,$order_sn,$id,$this->json('source'));
            }
            
        }elseif(time() < $card->term_end_time){
            $dgcss = $card->dgcs + 1;
            if($card->data > $card->total_flow){
                $pack = $card->data + $package->data;
            }else{
                $pack = $card->total_flow + $package->data;
            }
            $length = $card->term_length;
            $card->updateAttributes(['package_id'=>$this->json('package_id'),'term_length'=>$length,'total_flow'=>$pack,'dgcs'=>$dgcss]);
            $second_recharge = $card->stopNetworkAccess($card->iccid);
            Yii::$app->db->createCommand()->update('card', ['limit_type'=>0], 'id = :id',['id' => $card->id])->execute();  
        }
        $active_card = $card->setActive($card->iccid);
        return [];
    }
    public function setReserver($agent_id,$card_id,$iccid,$package_id,$endtime,$order_sn,$id,$source)
    {
        $term_length = 1;
        //查询package_sub
        $connection  = Yii::$app->db;
        $sql     = "select * from package_sub";
        $command = $connection->createCommand($sql);
        $res     = $command->queryAll();
        $json = json_decode($res[0]['package_sub'],true);
        
        foreach ($json as $key => $value) {
            $keys = $key - 2;
            $k = $key - 1;
            $reserve = new UserCardReserveRecharge();
            $reserve->agent_id = $agent_id;
            if($key == 1){
                continue;
            }
            if($key == 2){
                $reserve->package_id = $value;
                $reserve->price = '99';
                $reserve->money = '99';
            }elseif($key >2 && $key <=4){
                $reserve->package_id = $value;
                $reserve->price = '99';
                $reserve->money = '99';
            }elseif($key > 4){
                $reserve->package_id = $value;
                $reserve->price = '99';
                $reserve->money = '99';
            }
            $reserve->card_id = $card_id;
            $reserve->iccid = $iccid;
            $reserve->term_length = $term_length;
            $reserve->term_length_unit = '3';
            $reserve->trade_type = '1';
            $reserve->order_sn = $order_sn."-".$key;
            $reserve->status = UserCardReserveRecharge::STATUS_PAID;
            $reserve->create_time = time();
            $reserve->pay_time = time();
            if($key == 2){
                $date = strtotime(date("Y-m-d",strtotime('+'.$keys.'month',$endtime))) + 86400;
                $endate = strtotime(date("Y-m-d",strtotime('+'.$k.'month',$endtime)))  + 86399;
            }else{
                $date = strtotime(date("Y-m-d",strtotime('+'.$keys.'month',$endtime))) + 86400;
                $endate = strtotime(date("Y-m-d",strtotime('+'.$k.'month',$endtime)))  + 86399;
            }
            $reserve->active_time = $date;
            $reserve->term_end_time = $endate;
            $reserve->trade_no = $order_sn;
            $reserve->card_recharge_id = $id;
            $reserve->source = $source;
            $reserve->save();
        }
        
    }
    
    
    //年包充值拆分类型2
    private function setReserverOrder($agent_id,$card_id,$iccid,$package_id,$endtime,$order_sn,$id,$source)
    {
        $term_length = 1;
        
        //查询package_sub
        $connection  = Yii::$app->db;
        $sql     = "select * from package_sub";
        $command = $connection->createCommand($sql);
        $res     = $command->queryAll();
        $json = json_decode($res[1]['package_sub'],true);
        $pack = Package::findOne(['id'=>$json[1]]);
        foreach ($json as $key => $value) {
            $keys = $key - 2;
            $k = $key - 1;
            $reserve = new UserCardReserveRecharge();
            $reserve->agent_id = $agent_id;
            if($key == 1){
                continue;
            }
            $reserve->package_id = $pack['id'];
            $reserve->price = $pack['price'];
            $reserve->money = $pack['price'];
            $reserve->card_id = $card_id;
            $reserve->iccid = $iccid;
            $reserve->term_length = $term_length;
            $reserve->term_length_unit = '3';
            $reserve->trade_type = '1';
            $reserve->order_sn = $order_sn."-".$key;
            $reserve->status = UserCardReserveRecharge::STATUS_PAID;
            $reserve->create_time = time();
            $reserve->pay_time = time();
            if($key == 2){
                $date = strtotime(date("Y-m-d",strtotime('+'.$keys.'month',$endtime))) + 86400;
                $endate = strtotime(date("Y-m-d",strtotime('+'.$k.'month',$endtime)))  + 86399;
            }else{
                $date = strtotime(date("Y-m-d",strtotime('+'.$keys.'month',$endtime))) + 86400;
                $endate = strtotime(date("Y-m-d",strtotime('+'.$k.'month',$endtime)))  + 86399;
            }
            $reserve->active_time = $date;
            $reserve->term_end_time = $endate;
            $reserve->trade_no = $order_sn;
            $reserve->card_recharge_id = $id;
            $reserve->source = $source;
            $reserve->save();
        }
        
    }
    //年包100G拆分
    private function setReserverOrderYear($agent_id,$card_id,$iccid,$endtime,$order_sn,$id,$source)
    {
        $term_length = 1;
        
        //查询package_sub
        $connection  = Yii::$app->db;
        $sql     = "select * from package_sub";
        $command = $connection->createCommand($sql);
        $res     = $command->queryAll();
        $json = json_decode($res[2]['package_sub'],true);
        $pack = Package::findOne(['id'=>$json[2]]);
        foreach ($json as $key => $value) {
            $keys = $key - 2;
            $end = $endtime + 1;
            $day = $keys * 30;
            $reserve = new UserCardReserveRecharge();
            $reserve->agent_id = $agent_id;
            if($key == 1){
                continue;
            }
            $reserve->package_id = $pack['id'];
            $reserve->price = $pack['price'];
            $reserve->money = $pack['price'];
            $reserve->card_id = $card_id;
            $reserve->iccid = $iccid;
            $reserve->term_length = $term_length;
            $reserve->term_length_unit = '3';
            $reserve->trade_type = '1';
            $reserve->order_sn = $order_sn."-".$key;
            $reserve->status = UserCardReserveRecharge::STATUS_PAID;
            $reserve->create_time = time();
            $reserve->pay_time = time();
            $date =  $end + (86400*$day);
            $reserve->active_time = $date;
            $reserve->trade_no = $order_sn;
            $reserve->card_recharge_id = $id;
            $reserve->source = $source;
            $reserve->save();
        }
        
    }
    //半年包100G拆分
    private function setReserverOrderHalf($agent_id,$card_id,$iccid,$endtime,$order_sn,$id,$source)
    {
        $term_length = 1;
        
        //查询package_sub
        $connection  = Yii::$app->db;
        $sql     = "select * from package_sub";
        $command = $connection->createCommand($sql);
        $res     = $command->queryAll();
        $json = json_decode($res[3]['package_sub'],true);
        $pack = Package::findOne(['id'=>$json[3]]);
        foreach ($json as $key => $value) {
            $keys = $key - 2;
            $end = $endtime + 1;
            $day = $keys * 30;
            $reserve = new UserCardReserveRecharge();
            $reserve->agent_id = $agent_id;
            if($key == 1){
                continue;
            }
            $reserve->package_id = $pack['id'];
            $reserve->price = $pack['price'];
            $reserve->money = $pack['price'];
            $reserve->card_id = $card_id;
            $reserve->iccid = $iccid;
            $reserve->term_length = $term_length;
            $reserve->term_length_unit = '3';
            $reserve->trade_type = '1';
            $reserve->order_sn = $order_sn."-".$key;
            $reserve->status = UserCardReserveRecharge::STATUS_PAID;
            $reserve->create_time = time();
            $reserve->pay_time = time();
            $date =  $end + (86400*$day);
            $reserve->active_time = $date;
            $reserve->trade_no = $order_sn;
            $reserve->card_recharge_id = $id;
            $reserve->source = $source;
            $reserve->save();
        }
        
    }
    //季度充值拆分订单
    private function setReserverOrderSeason($agent_id,$card_id,$iccid,$package_id,$endtime,$order_sn,$id,$source)
    {
        $term_length = 1;
        
        //查询package_sub
        $connection  = Yii::$app->db;
        $sql     = "select * from package_sub";
        $command = $connection->createCommand($sql);
        $res     = $command->queryAll();
        $json = json_decode($res[8]['package_sub'],true);
        $package = Package::findOne(['id'=>$package_id]);
        foreach ($json as $key => $value) {
            $keys = $key - 2;
            $end = $endtime + 1;
            $day = $keys * 30;
            $reserve = new UserCardReserveRecharge();
            $reserve->agent_id = $agent_id;
            if($key == 1){
                continue;
            }
            $reserve->package_id = $package->id;
            $reserve->price = $package->price;
            $reserve->money = $package->price;
            $reserve->card_id = $card_id;
            $reserve->iccid = $iccid;
            $reserve->term_length = $term_length;
            $reserve->term_length_unit = '3';
            $reserve->trade_type = '1';
            $reserve->order_sn = $order_sn."-".$key;
            $reserve->status = UserCardReserveRecharge::STATUS_PAID;
            $reserve->create_time = time();
            $reserve->pay_time = time();
            $date =  $end + (86400*$day);
            $reserve->active_time = $date;
            $reserve->trade_no = $order_sn;
            $reserve->card_recharge_id = $id;
            $reserve->source = $source;
            $reserve->save();
        }
        
    }

    //铭信预定
    private function setAgentReserve($agent_id,$card_id,$iccid,$package_id,$endtime,$order_sn,$id)
    {
        $term_length = 1;
        $reserve = UserCardReserveRecharge::find()->orderBy('id desc')->andWhere(['like','iccid',$iccid])->andWhere(['execute_status'=>2])->one();
        if(empty($reserve)){
            $date = $endtime + 1;
        }else{
            $date = $reserve['active_time'] + (30*86400);
        }
        $order_sn = date('YmdHis').rand(1000, 9999);
        $pack = Package::findOne(['id'=>$package_id]);
        $reserve = new UserCardReserveRecharge();
        $reserve->agent_id = $agent_id;
        $reserve->package_id = $package_id;
        $reserve->price = $pack['price'];
        $reserve->money = $pack['price'];
        $reserve->card_id = $card_id;
        $reserve->iccid = $iccid;
        $reserve->term_length = $term_length;
        $reserve->term_length_unit = '3';
        $reserve->trade_type = '3';
        $reserve->order_sn = $order_sn;
        $reserve->status = UserCardReserveRecharge::STATUS_PAID;
        $reserve->create_time = time();
        $reserve->pay_time = time();
        $reserve->active_time = $date;
        $reserve->trade_no = $order_sn;
        $reserve->source = '8';
        $reserve->card_recharge_id = $id;
        $reserve->save();
        
    }
    
    
    //微信端充值季度、半年、年套餐
    private function setReserve($agent_id,$card_id,$iccid,$package_id,$endtime,$order_sn,$id,$source)
    {
        $term_length = 1;
        $package = Package::findOne(['id'=>$package_id]);
        //查询package_sub
        $connection  = Yii::$app->db;
        $sql     = "select * from package_sub";
        $command = $connection->createCommand($sql);
        $res     = $command->queryAll();
        if($package->length_unit == 1){
            $json = json_decode($res[8]['package_sub'],true);
        }elseif($package->length_unit == 2) {
            $json = json_decode($res[7]['package_sub'],true);
        }elseif($package->length_unit == 3){
            $json = json_decode($res[4]['package_sub'],true);
        }
        
        foreach ($json as $key => $value) {
            $keys = $key - 2;
            $end = $endtime + 1;
            $day = $keys * 30;
            $reserve = new UserCardReserveRecharge();
            $reserve->agent_id = $agent_id;
            if($key == 1){
                continue;
            }
            $reserve->package_id = $package->id;
            $reserve->price = $package->price;
            $reserve->money = $package->price;
            $reserve->card_id = $card_id;
            $reserve->iccid = $iccid;
            $reserve->term_length = $term_length;
            $reserve->term_length_unit = '3';
            $reserve->trade_type = '1';
            $reserve->order_sn = $order_sn."-".$key;
            $reserve->status = UserCardReserveRecharge::STATUS_PAID;
            $reserve->create_time = time();
            $reserve->pay_time = time();
            $date =  $end + (86400*$day);
            $reserve->active_time = $date;
            $reserve->trade_no = $order_sn;
            $reserve->card_recharge_id = $id;
            $reserve->source = $source;
            $reserve->save();
        }
        
    }
    //预定充值
    private function setReserveRecharge($agent_id,$card_id,$iccid,$package_id,$active_time,$order_sn,$id)
    {
        $package = Package::findOne(['id'=>$package_id]);
        //查询package_sub
        $connection  = Yii::$app->db;
        $sql     = "select * from package_sub";
        $command = $connection->createCommand($sql);
        $res     = $command->queryAll();
        if($package->length_unit == 1){
            $json = json_decode($res[8]['package_sub'],true);  
        }elseif($package->length_unit == 2) {
            $json = json_decode($res[7]['package_sub'],true);
        }elseif($package->length_unit == 3){
            $json = json_decode($res[4]['package_sub'],true);
        }
        foreach ($json as $key => $value) {
            $keys = $key - 1;
            $day = $keys * 30;
            $recharge = new UserCardReserveRecharge();
            $recharge->agent_id = $agent_id;
            $recharge->package_id = $package->id;
            $recharge->card_id = $card_id;
            $recharge->iccid = $iccid;
            $recharge->term_length = $this->json('term_length');
            $recharge->term_length_unit = UserCardReserveRecharge::TERM_LENGTH_UNIT_MONTH;
            $recharge->price = $package->price;
            $recharge->money = $package->price;
            $recharge->trade_type = $this->json('trade_type');
            $recharge->trade_no = $this->json('trade_no');
            $recharge->status = UserCardReserveRecharge::STATUS_PAID;
            $recharge->create_time = time();
            $recharge->pay_time = time();
            $date = strtotime(date("Y-m-d",strtotime('+'.$day.'days',$active_time)));
            $recharge->active_time = $date;
            $recharge->source = $this->json('source');
            $recharge->order_sn = $order_sn."-".$key;
            $recharge->card_recharge_id = $id;
            $recharge->save();
        }
        
    }

    //体验套餐激活
    public function actionExpActive(){
        if ($this->app_id != 'weixin') {
            throw new ApiException('FORBIDDEN', '没有权限。');
        }

        $this->checkJson([
            [['card', 'trade_type', 'source'], 'required'],
        ]);
        
        $card = $this->getCard(null, 'card/');
        if (empty($card)) {
            throw new ApiException('NOT_FOUND', '没有找到卡信息。');
        }
        
        $package = Package::findOne(['id'=> $card->package_id]);
        if(empty($package)){
            throw new ApiException('NO_PACKAGE', '卡没有设置套餐。');
            
        }
        if($card->package_id != '98'){
            throw new ApiException('COULD_NOT_EXECUTE', '套餐无法激活');
            exit;
            
        }
        if($card->agent_id != '809'){
            throw new ApiException('NO_AGENT', '代理商无法激活');
            exit;
            
        }
        if($card->active_time != 0){
            throw new ApiException('COULD_NOT_EXECUTE_TWICE', '套餐已经激活，无法再次激活！');
            exit;
        }
        $term_length = 1;
        $endate = time() + (29*86400);
        $endtime = strtotime(date('Y-m-d',$endate))+86399;
        
        //获取当前周期结束日期
        if($card->status != 4){
        $end_date = time() + (29*86400);
        $end_time = strtotime(date('Y-m-d',$end_date))+86399;
        if($card->order_time == '0'){
            $order_time = time();
        }else{
            $order_time = $card->order_time;
        }
        $order_sn = date('YmdHis').rand(1000, 9999);

        $recharge = new UserCardRecharge();
        $recharge->uid = $card->uid;
        $recharge->agent_id = $card->agent_id;
        $recharge->package_id = $package->id;
        $recharge->card_id = $card->id;
        $recharge->term_length = $term_length;
        $recharge->term_length_unit = UserCardRecharge::TERM_LENGTH_UNIT_MONTH;
        $recharge->price = $package->price;
        $recharge->money = $package->price;
        $recharge->trade_type = $this->json('trade_type');
        $recharge->trade_no = $order_sn;
        $recharge->trans_id = '';
        $recharge->status = UserCardRecharge::STATUS_PAID;
        $recharge->create_time = time();
        $recharge->pay_time = time();
        $recharge->update_time = time();
        $recharge->remark = '';
        $recharge->source = $this->json('source');
        if($card->term_end_time == '0'){
            if($card->dgcs == '0'){
                $recharge->recharge_type = '1';
            }
            
        }else{
            $recharge->recharge_type = '2';
        }

        $recharge->save();
        $id = $recharge->attributes['id'];
        $recharges = UserCardRecharge::findOne(['id' => $id]);
        if($card->package_id != '98'){
           $recharges->setPaid();   
        }
        
           
        }

        if($card->term_end_time == '0'){
            $dgcss = $card->dgcs + 1;
                $card->updateAttributes(
                ['package_id'=>$package->id,'active_time' => time(),'data'=>0,'term_length'=>$term_length,'total_flow'=>$package->data,'term_end_time'=>$endtime,'order_time'=>$order_time,'term_length_unit'=>3,'order_sn'=>$order_sn,'dgcs'=> $dgcss, 'status' => Card::STATUS_ACTIVATED
                ]
            );
                
                $cardDatalog = new CardDatalog();
                $cardDatalog->card_id = $card->id;
                $cardDatalog->startdate = time();
                $cardDatalog->enddate = $endate;
                $cardDatalog->order_sn = $order_sn;
                $cardDatalog->data = 0;
                $cardDatalog->saveDataLog();
            
        }
        $active_card = $card->setActive($card->iccid);
        return [];
    }

}
